//
//  TablesScreenView.m
//  ServiceApp
//
//  Created by User-23 on 12/10/14.
//  Copyright (c) 2014 TrainingCamp. All rights reserved.
//

#import "TablesScreenView.h"
#import "Table.h"
#import "TableCell.h"
#import "OrderDetailForTable.h"
#import "TablesManager.h"
#import "NotificationManager.h"
#import "Notification.h"
#import "BillsManager.h"

@interface TablesScreenView ()

@property TablesManager *tables;

@property NotificationManager* noteManager;

@property BOOL loadedInitialNotes;
@end

@implementation TablesScreenView

static NSString * const reuseIdentifier = @"Cell";
static NSString* kLogOutUrl = @"http://78.90.20.186:8080/ProjectRestaurant/LogoutWaiter";



#pragma mark - View Setup

- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    
    self.navigationController.navigationBar.hidden = YES;
    self.tabBarController.tabBar.hidden = NO;
    
    [[[[self.tabBarController tabBar]items]objectAtIndex:0]setEnabled:NO];

    
    [self.tables update];
    
    [[TablesManager sharedTables] selectTableWithIndex:-1];
    
    //Show Bottom Bar
    self.navigationController.toolbarHidden = NO;
    
    //Listen for server messages
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(displayNotification:)
                                                 name:@"NewNotification"
                                               object:nil];
    
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(messageBadge)
                                                 name:@"Notification"
                                               object:nil];
}



- (void)viewDidLoad {
    [super viewDidLoad];
    
    
    //Disable swipe to go back gesture
    self.navigationController.interactivePopGestureRecognizer.delegate = self;

    if ([self.navigationController respondsToSelector:@selector(interactivePopGestureRecognizer)]) {
        self.navigationController.interactivePopGestureRecognizer.enabled = NO;
    }
    //Load tables
    self.tables = [TablesManager sharedTables];
    
    //Listen for table update events
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(update:)
                                                 name:@"table" object:nil];
    
    
    // Register cell classes
    [self.collectionView registerClass:[UICollectionViewCell class] forCellWithReuseIdentifier:reuseIdentifier];
    [self.collectionView registerNib:[UINib nibWithNibName:@"TableCell" bundle:nil] forCellWithReuseIdentifier:@"tableCell"];
    // Do any additional setup after loading the view.
    
    self.noteManager = [NotificationManager sharedNotifications];

}

-(void)viewDidDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];

    [[NSNotificationCenter defaultCenter] removeObserver:self
                                                    name:@"NewNotification"
                                                  object:nil];
}

- (void) update:(NSNotification*) note {
    dispatch_async(dispatch_get_main_queue(), ^{
        [self.collectionView reloadData];

    });
}

- (IBAction)logOutButton:(id)sender {
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Logging Out"
                                                    message:@"You are about to log out. Are you sure?"
                                                   delegate:self
                                          cancelButtonTitle:@"LOG OUT"
                                          otherButtonTitles:@"CANCEL", nil];
    [alert show];
}

#pragma mark Collection View Data Source Methods

- (UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout insetForSectionAtIndex:(NSInteger)section {
//    CGFloat rightEdge = 200.0;
//    CGFloat inset = collectionView.frame.size.width-rightEdge;
//    
//    CGFloat collectionViewHeight = CGRectGetHeight(collectionView.bounds);
//    CGFloat collectionViewWidth = CGRectGetWidth(collectionView.bounds);
//    [collectionView setContentInset:UIEdgeInsetsMake(collectionViewHeight/2, collectionViewWidth/4, collectionViewHeight/2, collectionViewWidth/4) ];
//    //                               animated:YES];
//    // Only center align if the inset is greater than 0
//    // That means that the total width of the cells is less than the width of the collection view and need to be aligned to the center.
//    // Otherwise let them align left with no indent.
//    
////    if(inset > 0)
////        return UIEdgeInsetsMake(0.0, inset/2, 0.0, 10.0);
////    else
////        return UIEdgeInsetsMake(0, 0, 0, 0);
    return UIEdgeInsetsMake(50, 50, 0, 50);// top , left, bottom, right
}

- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView {
    return 1;
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    return [self.tables count];
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    
    NSString * cellID = @"tableCell";
    
    TableCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:cellID forIndexPath:indexPath];
    cell.backgroundColor = [UIColor whiteColor];
    
    switch ([self.tables pendingOrderForTableAtIndex:indexPath.row]) {
        case 0:
            cell.backgroundColor = [UIColor greenColor];
            break;
        case 1:
            cell.backgroundColor = [UIColor yellowColor];
            break;
        default:
            break;
    }


    
    if ([self.tables messageForTableAtIndex:indexPath.row]){
        cell.backgroundColor = [UIColor redColor];
    }
    cell.tableNumberLabel.text = [NSString stringWithFormat:@"%ld", (long)[self.tables getNumberForTableAtIndex:indexPath.row]];
    
    return cell;
}

#pragma mark Collection View Delegate Methods

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
    [[TablesManager sharedTables] selectTableWithIndex:indexPath.row];
    [BillsManager getBillForTable:[[TablesManager sharedTables] selectedTable]];
    [self performSegueWithIdentifier:@"TableToOrder" sender:self];
}

#pragma mark Alert View Delagate Methods

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{
    if (buttonIndex == 0){
        NSURLSession* session = [NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];
        
        NSURL *url = [NSURL URLWithString:kLogOutUrl];
        NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url cachePolicy:0 timeoutInterval:60];
        
        [request setHTTPMethod:@"POST"];
        [request setValue:@"application/json" forHTTPHeaderField:@"Accept"];
        [request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
        
        NSURLSessionDataTask* postDataTask = [session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
            NSError* mistake = nil;
            if (mistake != nil) {
                NSLog(@"Error : %@", [mistake localizedDescription]);
            }
            else {
                dispatch_async(dispatch_get_main_queue(), ^{
                    [self.navigationController popViewControllerAnimated:YES];
                });
            }           
            
        }];
        [postDataTask resume];
        
    }
    else
    {
        NSLog(@"cancel");
    }
}

- (IBAction)messageButton:(id)sender {
    NSDictionary *dict = [[NSDictionary alloc] initWithObjectsAndKeys:@3, @"tableId", @"Calling Waiter!", @"text", nil];
    
    if ([NSJSONSerialization isValidJSONObject:dict]) {
        
        NSError *error = nil;
        NSData *jsonRequestData = [NSJSONSerialization dataWithJSONObject:dict options:NSJSONWritingPrettyPrinted error:&error];
        
        if (error == nil && jsonRequestData != nil) {
            NSURLSession* session = [NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];
            NSURL *url = [NSURL URLWithString:@"http://78.90.20.186:8080/ProjectRestaurant/makeMessage"];
            NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url cachePolicy:0 timeoutInterval:60];
            
            [request setHTTPMethod:@"POST"];
            [request setValue:@"application/json" forHTTPHeaderField:@"Accept"];
            [request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
            [request setValue:[NSString stringWithFormat:@"%lu", (unsigned long)[jsonRequestData length]] forHTTPHeaderField:@"Content-Length"];
            [request setHTTPBody:jsonRequestData];
            
            
            NSURLSessionDataTask* postDataTask = [session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
                NSError* mistake = nil;
                if (mistake != nil) {
                    NSLog(@"Error : %@", [mistake localizedDescription]);
                }
                else {
                    dispatch_async(dispatch_get_main_queue(), ^{
                    });
                }
                
            }];
            [postDataTask resume];
        }
    }
}

- (void) displayNotification:(NSNotification*) note{
    Notification* message = note.object;
    dispatch_async(dispatch_get_main_queue(), ^{        
        UIAlertView* alert = [[UIAlertView alloc] initWithTitle:[NSString stringWithFormat:@"%@", message.text]
                                                        message:[NSString stringWithFormat:@"Table: %ld", (long)message.tableId]
                                                       delegate:nil
                                              cancelButtonTitle:@"OK"
                                              otherButtonTitles:nil];
        [alert show];
    });
   
}

- (void) messageBadge{   
    NSInteger count = [[NotificationManager sharedNotifications] count];
    NSString* newValue = [NSString stringWithFormat:@"%ld", (long) count];
    UIViewController* vc = self.tabBarController.viewControllers[1];
    dispatch_async(dispatch_get_main_queue(), ^{
        vc.tabBarItem.badgeValue = newValue;
    });
}

@end
